/*
 * @Author: 鱼得水
 * @Date: 2024-02-13 23:16:48
 * @LastEditTime: 2024-02-22 18:08:44
 * @Description:
 */
import { createRouter, createWebHistory } from "vue-router";

//#region 自动路由
// 读取所有的 pages.js文件
const pages = import.meta.glob("../views/**/pages.js", {
  eager: true,
  import: "default",
});

// 读取所有的 doc.md文件
const pageMD = import.meta.glob("../views/**/doc.md", {
  import: "default",
});

const pageComps = import.meta.glob("../views/**/index.vue", {
  import: "default",
});

// 自动doc.md路由
const autoDocRouter = Object.entries(pages).map(([path, meta]) => {
  let pageComPath = path;
  path = path.replace("../views", "").replace("/pages.js", "");
  path = path || "/";
  // 获得子路由路径
  let childrenPath = path.substring(1);
  const name = "doc-" + path.split("/").filter(Boolean).join("-");
  const comPath = pageComPath.replace("pages.js", "doc.md");
  return {
    // 路由路径
    path: childrenPath,
    name,
    meta,
    component: pageMD[comPath],
  };
});

// 自动页面路由
const autoPagesRouter = Object.entries(pages).map(([path, meta]) => {
  let pageComPath = path;
  path = path.replace("../views", "").replace("/pages.js", "");
  // 处理当path为空的情况，例如首页路由路径
  path = path || "/";
  // console.log(path)
  const name = path.split("/").filter(Boolean).join("-") || "index";
  // console.log(name)
  const comPath = pageComPath.replace("pages.js", "index.vue");
  return {
    // 路由路径
    path,
    name,
    meta,
    component: pageComps[comPath],
  };
});
//#endregion

// 路由表
const routes = [
  // {path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('../views/404.vue'), meta: { title: '404' } },
  { path: "/", redirect: "/index" },
  {
    path: "/index",
    name: "index",
    component: () => import("../views/index.vue"),
    meta: { title: "首页" },
  },
  {
    path: "/doc",
    redirect: "/doc/readme",
    name: "doc-reader",
    component: () => import("../views/docReader.vue"),
    meta: { title: "DocReder" },
    children: [
      {
        path: "readme",
        name: "doc-readme",
        meta: { title: "vite-doc 介绍" },
        component: () => import("@views/doc.md"),
      },
      ...autoDocRouter,
    ],
  },
  ...autoPagesRouter,
  {
    // /:catchAll(.*) 匹配任意路径
    // 当前面所有的路由都匹配失败
    // 就会被当前路由捕获
    // 然后跳转到404页面
    path: "/:catchAll(.*)",
    component: () => import("@views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
export default router;
router.beforeEach((to, from, next) => {
  // 当路由路径为doc时，设置标题为MD - xxx
  let path = to.path;
  if (path.split("/").filter(Boolean)[0] == "doc" && to.meta.title) {
    document.title = "MD - " + to.meta.title;
    return next();
  }
  // 读取路由元信息设置标题
  if (to.meta.title) {
    document.title = to.meta.title;
  } else {
    document.title = "ViteDoc";
  }
  next();
});
